Coursework 1: Image filtering¶

In this coursework you will practice techniques for image filtering. The coursework includes coding questions and written questions. Please read both the text and the code in this notebook to get an idea what you are expected to implement.

What to do?¶

  • Complete and run the code using jupyter-lab or jupyter-notebook to get the results.

  • Export (File | Save and Export Notebook As...) the notebook as a PDF file, which contains your code, results and answers, and upload the PDF file onto Scientia.

  • Instead of clicking the Export button, you can also run the following command instead: jupyter nbconvert coursework_01_solution.ipynb --to pdf

  • If Jupyter complains about some problems in exporting, it is likely that pandoc (https://pandoc.org/installing.html) or latex is not installed, or their paths have not been included. You can install the relevant libraries and retry. Alternatively, use the Print function of your browser to export the PDF file.

  • If Jupyter-lab does not work for you at the end (we hope not), you can use Google Colab to write the code and export the PDF file.

Dependencies:¶

You need to install Jupyter-Lab (https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html) and other libraries used in this coursework, such as by running the command: pip3 install [package_name]

In [ ]:
# Import libaries (provided)
import imageio.v3 as imageio
import numpy as np
import matplotlib.pyplot as plt
import noise
import scipy
import scipy.signal
import math
import time

1. Moving average filter (20 points).¶

Read the provided input image, add noise to the image and design a moving average filter for denoising.

You are expected to design the kernel of the filter and then perform 2D image filtering using the function scipy.signal.convolve2d().

In [ ]:
# Read the image (provided)
image = imageio.imread('campus_snow.jpg')
plt.imshow(image, cmap='gray')
plt.gcf().set_size_inches(8, 8)
In [ ]:
# Corrupt the image with Gaussian noise (provided)
image_noisy = noise.add_noise(image, 'gaussian')
plt.imshow(image_noisy, cmap='gray')
plt.gcf().set_size_inches(8, 8)

Note: from now on, please use the noisy image as the input for the filters.¶

1.1 Filter the noisy image with a 3x3 moving average filter. Show the filtering results.¶

In [ ]:
# Design the filter h
### Insert your code ###
h = np.full((3,3),1/9)#.array([[1/9,1/9,1/9] for i in range(3)])

# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h)

# Print the filter (provided)
print('Filter h:')
print(h)

# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h:
[[0.11111111 0.11111111 0.11111111]
 [0.11111111 0.11111111 0.11111111]
 [0.11111111 0.11111111 0.11111111]]

1.2 Filter the noisy image with a 11x11 moving average filter.¶

In [ ]:
# Design the filter h
### Insert your code ###
h = np.full((11,11),1/121)

# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h)

# Print the filter (provided)
print('Filter h:')
print(h)

# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h:
[[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]]

1.3 Comment on the filtering results. How do different kernel sizes influence the filtering results?¶

The moving average filters were successful in reducing noise in the image but not completely. The 3x3 kernel produces a cleaner and sharper image compared to the 11x11 filter because it takes the average across a smaller area of the whole picture compared to an 11x11 grid of pixels. The 11x11 filter averages out a large area to reduce more noise than the 3x3, but it results in a blurrier image due to its lack of range.

2. Edge detection (56 points).¶

Perform edge detection using Sobel filtering, as well as Gaussian + Sobel filtering.

2.1 Implement 3x3 Sobel filters and convolve with the noisy image.¶

In [ ]:
# Design the filters
### Insert your code ###
sobel_x = np.array([[1,0,-1],[2,0,-2],[1,0,-1]])
sobel_y = np.array([[1,2,1],[0,0,0],[-1,-2,-1]])

# Image filtering
### Insert your code ###
image_x = scipy.signal.convolve2d(image_noisy, sobel_x)
image_y = scipy.signal.convolve2d(image_noisy,sobel_y)

# Calculate the gradient magnitude
grad_mag = np.sqrt(np.square(image_x) + np.square(image_y))

# Print the filters (provided)
print('sobel_x:')
print(sobel_x)
print('sobel_y:')
print(sobel_y)
# Display the magnitude map (provided)
plt.imshow(grad_mag, cmap='gray')#grad_mag,cmap='gray')
plt.gcf().set_size_inches(8, 8)
sobel_x:
[[ 1  0 -1]
 [ 2  0 -2]
 [ 1  0 -1]]
sobel_y:
[[ 1  2  1]
 [ 0  0  0]
 [-1 -2 -1]]

2.2 Implement a function that generates a 2D Gaussian filter given the parameter $\sigma$.¶

In [ ]:
# Design the Gaussian filter
def gaussian_filter_2d(sigma):
    # sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
    #
    # return: a 2D array for the Gaussian kernel
    
    ### Insert your code ###
    const = 1/(2*np.pi*(np.square(sigma)))
    size = int(2*k*sigma)+1
    centre = (size-1)/2 #assuming kernel size is odd
    h = np.zeros((size,size))
    for i in range(size):
        for j in range(size):
            x,y = i- centre, j-centre
            fraction  = ((np.square(x))+(np.square(y)))/(2*(np.square(sigma)))        
            h[i,j] = const*(np.exp(-1*fraction))

    h = h/np.sum(h) #normalising
    return h

# Visualise the Gaussian filter when sigma = 5 pixel (provided)
k = 3 
sigma = 5
h = gaussian_filter_2d(sigma)
plt.imshow(h)
Out[ ]:
<matplotlib.image.AxesImage at 0x156ecef8580>

2.3 Perform Gaussian smoothing ($\sigma$ = 5 pixels) and evaluate the computational time for Gaussian smoothing. After that, perform Sobel filtering and show the gradient magintude map.¶

In [ ]:
# Construct the Gaussian filter
gauss_filter = gaussian_filter_2d(5)

# Perform Gaussian smoothing and count time
start_time = time.time()
gauss_img = scipy.signal.convolve2d(image_noisy, gauss_filter)
end_time = time.time()
time_taken = end_time - start_time
print("time taken", time_taken)
#built_in_gauss_img = scipy.ndimage.gaussian_filter(image_noisy,sigma = 5) #inbuilt function

# Image filtering
image_x = scipy.signal.convolve2d(gauss_img,sobel_x)
image_y = scipy.signal.convolve2d(gauss_img,sobel_y)

# Calculate the gradient magnitude
grad_mag = np.sqrt(np.square(image_x) + np.square(image_y))
# Display the gradient magnitude map (provided)
plt.imshow(grad_mag, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
time taken 2.639841079711914

2.4 Implement a function that generates a 1D Gaussian filter given the parameter $\sigma$. Generate 1D Gaussian filters along x-axis and y-axis respectively.¶

In [ ]:
# Design the Gaussian filter
def gaussian_filter_1d(sigma):
    # sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
    #
    # return: a 1D array for the Gaussian kernel
    
    size = int(2*k*sigma)+1
    centre = (size-1)/2 #assuming kernel size is odd
    h = np.zeros ((1,size))
    const = 1/(sigma* np.sqrt(2*np.pi))
    for i in range(size):
            x = i- centre
            fraction  = (np.square(x))/(2*(np.square(sigma)))        
            h[0,i] = const*(np.exp(-1*fraction))
    h = h/np.sum(h)

    return h

# sigma = 5 pixel (provided)
sigma = 5

# The Gaussian filter along x-axis. Its shape is (1, sz).
### Insert your code ###
h_x = gaussian_filter_1d(sigma) 

# The Gaussian filter along y-axis. Its shape is (sz, 1).
### Insert your code ###
h_y = np.transpose(h_x)

# Visualise the filters (provided)
plt.subplot(1, 2, 1)
plt.imshow(h_x)
plt.subplot(1, 2, 2)
plt.imshow(h_y)
Out[ ]:
<matplotlib.image.AxesImage at 0x156ea604580>

2.6 Perform Gaussian smoothing ($\sigma$ = 5 pixels) using two separable filters and evaluate the computational time for separable Gaussian filtering. After that, perform Sobel filtering, show the gradient magnitude map and check whether it is the same as the previous one without separable filtering.¶

In [ ]:
# Perform separable Gaussian smoothing and count time

start_time = time.time()
blurred_img_x = scipy.signal.convolve2d(image_noisy, h_x)
blurred_img = scipy.signal.convolve2d(blurred_img_x, h_y)
end_time = time.time()
time_taken = end_time - start_time
print("time taken", time_taken)

# Image filtering
image_x = scipy.signal.convolve2d(blurred_img,sobel_x)
image_y = scipy.signal.convolve2d(blurred_img,sobel_y)

# Calculate the gradient magnitude
grad_mag2 = np.sqrt(np.square(image_x) + np.square(image_y))

# Display the gradient magnitude map (provided)
plt.imshow(grad_mag2, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)

# Check the difference between the current gradient magnitude map
# and the previous one produced without separable filtering. You
# can report the mean difference between the two.

mean_diff = np.mean(np.abs(grad_mag - grad_mag2))
print("Mean difference (grad1-grad2): ",mean_diff)
time taken 0.33431029319763184
Mean difference (grad1-grad2):  4.0727366025199697e-13

2.7 Comment on the Gaussian + Sobel filtering results and the computational time.¶

The results of using a 2D filter and two separable 1D filters is almost identical as seen both visually by the gradient magnitude plot and by the mean difference calculated. However, the computation time is much lower for separable filtering as seen in the timer results. This is because calculating the 2D kernel (size KxK) using nested for loops results in polynomial complexity - O(K2) whereas the separable filter kernels take O(K) time each. Considering this and the complexity of applying the kernels to an NxN image, the final complexity for the 2D filter is O(N2 K2) and O(2N2 K) for the separable filters. This is why computation time is lower when using separable filters.

3. Challenge: Implement 2D image filters using Pytorch (24 points).¶

Pytorch is a machine learning framework that supports filtering and convolution.

The Conv2D operator takes an input array of dimension NxC1xXxY, applies the filter and outputs an array of dimension NxC2xXxY. Here, since we only have one image with one colour channel, we will set N=1, C1=1 and C2=1. You can read the documentation of Conv2D for more detail.

In [ ]:
# Import libaries (provided)
import torch

3.1 Expand the dimension of the noisy image into 1x1xXxY and convert it to a Pytorch tensor.¶

In [ ]:
# Expand the dimension of the numpy array
new_img= np.expand_dims(image_noisy, axis = (0,1))


# Convert to a Pytorch tensor using torch.from_numpy
img_tensor = torch.from_numpy(new_img)

3.2 Create a Pytorch Conv2D filter, set its kernel to be a 2D Gaussian filter and perform filtering.¶

In [ ]:
# A 2D Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
img_tensor = img_tensor.double()
gauss= (gaussian_filter_2d(sigma))
tensor_h = torch.from_numpy (gauss).view(1, 1, gauss.shape[0],gauss.shape[1])
#print(tensor_h.shape)

# Create the Conv2D filter
conv_filter = torch.nn.Conv2d(1,1,(gauss.shape)).double()
conv_filter.weight.data = tensor_h.double()

# Filtering
image_filtered_tensor = conv_filter(img_tensor).double()
image_filtered  = image_filtered_tensor.detach().numpy()[0][0]

# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)

3.3 Implement Pytorch Conv2D filters to perform Sobel filtering on Gaussian smoothed images, show the gradient magnitude map.¶

In [ ]:
# Create Conv2D filters

sobel_x = torch.nn.Conv2d(1,1,3).double()
sobel_x.weight.data = torch.tensor([[[[1,0,-1],[2,0,-2],[1,0,-1]]]]).double()
sobel_y = torch.nn.Conv2d(1,1,3).double()
sobel_y.weight.data = torch.tensor([[[[1,2,1],[0,0,0],[-1,-2,-1]]]]).double()

# Perform filtering
x_grad = sobel_x(image_filtered_tensor).double()
y_grad = sobel_x(image_filtered_tensor).double()


# Calculate the gradient magnitude map
grad_mag3 = torch.sqrt(torch.pow(x_grad,2) + torch.pow(y_grad,2))
grad_mag3 = grad_mag3.detach().numpy()[0][0]

# Visualise the gradient magnitude map (provided)
plt.imshow(grad_mag3, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
In [ ]: